package com.tg.app.view;

import android.content.Context;
import android.content.res.Configuration;
import android.graphics.SurfaceTexture;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.tange.base.toolkit.AppUtil;
import com.tange.base.toolkit.DimenUtil;
import com.tange.base.toolkit.StringUtils;
import com.tg.app.R;
import com.tg.app.camera.AVIOCTRLDEFs;
import com.tg.app.helper.ActivityHelper;
import com.tg.app.helper.ResolutionHelper;
import com.tg.app.listener.OnZoomViewListener;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.android.TGLog;
import com.tg.data.http.entity.AVFrames;
import com.tg.data.media.OnMediaScaleChangedListener;
import com.tg.app.widget.ZoomPanTextureView;
import com.tange.base.toolkit.TGThreadPool;
import com.tg.data.bean.DeviceItem;

public class CameraPlayerSingleView extends CameraPlayerView{
    public static final String CUR_DEVICE_UUID = "cur_device_uuid";
    public static final String CUR_DEVICE_FEATURE = "cur_device_feature";
    private static final String TAG = "CameraPlayerSingleView";
    private float analogZoomScale;
    private boolean isOverAnalog;
    private float analogOverScaleEnd;
    private OnMediaScaleChangedListener scaleChangedListener;
    public CameraPlayerSingleView(Context context) {
        super(context);
    }

    public CameraPlayerSingleView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public CameraPlayerSingleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void init(Context context) {
        super.init(context);
        View view = LayoutInflater.from(context).inflate(R.layout.layout_camera_player_single, this);
        textureView  = view.findViewById(R.id.camera_player_view);
        bgView = view.findViewById(R.id.camera_player_view_bg);
        baseLayout = view.findViewById(R.id.player_single_base_layout);
        foreSightView =view.findViewById(R.id.camera_player_fore_sight_view);
        adjustPlayerUIHeight();
        setListener();
    }

    private void adjustPlayerUIHeight(){
        String uuid = (String)TGApplicationBase.getInstance().getGlobalObject(CUR_DEVICE_UUID);
        TGLog.d(TAG, "分辨率3：uuid = " + uuid);
        if (!StringUtils.isEmpty(uuid)){
            resolutionHelper = new ResolutionHelper(mContext, uuid);
            int h = resolutionHelper.calHeight(mWidth);
            int height = (int) getResources().getDimension(R.dimen.player_height);
            TGLog.d(TAG, "分辨率：h = " + h + ", height = " + height);
            if (h > 0 && h != height){
                updatePlayerViewSize(textureView, mWidth, h);
            }
        }
    }

    @Override
    protected int  getVideoSizeHeight(int height){
        int h =  super.getVideoSizeHeight(height);
        TGLog.d(TAG, "setLivePortraitLayout9 h = " + h + "height = " + height);
        int h1 = resolutionHelper.calHeight(mWidth);
        if (h1 > 0){
            return h1;
        }

        if (mediaSync.getAlignWidth() == 0 || mediaSync.getAlignHight() == 0){
            TGLog.d(TAG, "getAlignWidth == 0000");
            return h;
        }

        int h2 = mWidth * mediaSync.getAlignHight() / mediaSync.getAlignWidth();
        resolutionHelper.addAndSwitchResolution(mediaSync.getAlignWidth(), mediaSync.getAlignHight());
        TGLog.d(TAG, "setLivePortraitLayout9 h2 = " + h2 + "height = " + (mHeight - DimenUtil.dp2px(mContext, 50)));
        if (h2 <= mHeight - DimenUtil.dp2px(mContext, 50)){
            height = h2;
            return height;
        }
        TGLog.d(TAG, "setLivePortraitLayout9 height = " + height);
        return h;
    }

    @Override
    protected float getAspectRatio(){
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            float ratio = resolutionHelper.getAspectRatio();
            if (ratio > 0f){
                return ratio;
            }

            if (mediaSync != null){
                if (mediaSync.getAlignWidth() == 0 || mediaSync.getAlignHight() == 0){
                    super.getAspectRatio();
                }

                return (float) mediaSync.getAlignWidth() / mediaSync.getAlignHight();
            }
        }
        return super.getAspectRatio();
    }


    @Override
    public void setListener() {
        textureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
            @Override
            public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
                mediaSync.initMediaSync(textureView, nCodecId);
                mediaSync.setPlayType(getMediaType());
                setVideoSize(textureView,width, height);
                audioDecoder.start();
                textureUpdatedReset();
            }

            @Override
            public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
                TGLog.d(TAG, "onSurfaceTextureSizeChanged isUpdateViewSizeEnable:" + isUpdateViewSizeEnable + ", width = " + width + ", height = "  + height);
                if (!isUpdateViewSizeEnable)return;
                setVideoSize(textureView,width, height);
            }

            @Override
            public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
                mediaSync.stop();
                audioDecoder.stop();
                return false;
            }

            @Override
            public void onSurfaceTextureUpdated(SurfaceTexture surface) {
                textureUpdated();
                if (analogZoomScale>0&&!isOverAnalog){
                    TGLog.d(TAG, "analogZoom onSurfaceTextureUpdated");
                    textureView.analogZoom(analogZoomScale,0,false);
                    analogZoomScale = 0;
                }

            }
        });
        if (!isForeSightEnable){
            textureView.setZoomRange(1,4);
        }
        textureView.setOnZoomViewListener(new OnZoomViewListener() {
            @Override
            public void onSingleClick(boolean show) {
                if (onZoomViewListener!=null){
                    onZoomViewListener.onSingleClick(show);
                }
            }

            @Override
            public void onScale(float scale) {
                if (onZoomViewListener!=null){
                    onZoomViewListener.onScale(scale);
                }
            }
        });
        scaleChangedListener = () ->{
            TGLog.d(TAG, "analogZoom OnMedia");
            TGThreadPool.executeOnUiThreadDelayed(() -> {
                if (isOverAnalog){
                    TGLog.d(TAG, "analogZoom OnMedia2 "+analogOverScaleEnd+" analogZoomScale: "+analogZoomScale);
                    textureView.analogZoom(analogOverScaleEnd,1000,false);
                    textureView.analogZoom(analogOverScaleEnd,analogZoomScale,1500,true);
                    analogZoomScale  = 0;
                    isOverAnalog = false;
                }
            },1000);
        } ;
    }

    @Override
    public void receiveVideoData(@NonNull AVFrames avFrame) {
        int codec = avFrame.getMediaCodec();
        fixMediaSyncOnce(codec);
        if (codec == AVIOCTRLDEFs.MEDIA_CODEC_UNKNOWN){
            if (avFrame.getFlags()==1&&avFrame.getTimestamp()==0&&isOverAnalog){
                mediaSync.addVideo(avFrame);
            }
        }else {
            if (nCodecId>0&&nCodecId!=codec){
                TGThreadPool.executeOnUiThread(this::playerHide);
            }
            nCodecId = codec;
            mediaSync.addVideo(avFrame);
            if (textureView.getVisibility() != VISIBLE) {
                TGLog.d(TAG, "textureView.getVisibility() " + textureView.getVisibility());
                TGThreadPool.executeOnUiThread(() -> {
                    textureView.setVisibility(VISIBLE);
                    loadingHide();
                });

            }
        }
    }

    @Override
    public void receiveVideoMiniData(@NonNull AVFrames avFrame) {

    }

    @Override
    public void setAnchorView(View view) {

    }

    @Override
    public void setFloatView(View view) {

    }

    @Override
    public void setDevice(DeviceItem mDevice) {
        super.setDevice(mDevice);
        TGLog.i(TAG, "setDevice");

    }

    @Override
    protected void setBackgroundClick() {
        super.setBackgroundClick();
        bgView.setOnClickListener(onClickListener);
    }

    @Override
    protected void setBackgroundViewDrawable(Drawable resource) {
        bgView.setBackground(resource);
    }

    @Override
    protected void updatePlayerViewSize(ZoomPanTextureView textureView,int width, int height) {
        TGLog.d("CameraPlayerView", "CameraPlayerSingleView width: " + width + " height: " + height);
        setCurPlayerHeight(height);
        super.updatePlayerViewSize(textureView,width, height);
        ViewGroup.LayoutParams layoutParams = textureView.getLayoutParams();
        layoutParams.width = width;
        layoutParams.height = height;
        textureView.setLayoutParams(layoutParams);
        textureView.setVideoSize(width, height);
        TGLog.d("CameraPlayerView", "updatePlayerViewSize width: " + width + " height: " + height);
    }

    @Override
    public int updateCameraViewSize(){
        int h = super.updateCameraViewSize();
        if (h > 0){
            if (isLandscape()){
                updatePlayerViewSize(textureView, h, mWidth);
            }else{
                updatePlayerViewSize(textureView, mWidth, h);
            }

        }

        return h;
    }

    @Override
    public void updateView() {

    }

    @Override
    public void analogZoom(float scale, boolean animation,int duration, int index, String from) {
        if (isSurfaceTextureUpdated&&!isOverAnalog){
            TGLog.d(TAG, "analogZoom ==> "+scale);
            textureView.analogZoom(scale,duration,animation);
        }else {
            analogZoomScale = scale;
            TGLog.d(TAG, "analogZoom analogZoomScale "+scale);
        }
    }

    @Override
    public void analogOverZoom(float startScale, float endScale,int duration, int index) {
        this.isOverAnalog = true;
        analogOverScaleEnd = endScale;
        if (isSurfaceTextureUpdated){
            textureView.analogZoom(startScale,2000,true);
        }
    }

    @Override
    protected void updateListener() {
        mediaSync.setOnScreencapListener(onScreencapListener);
        mediaSync.setPlayListener(onMediaPlayListener);
        mediaSync.setFormatChangedListener(formatChangedListener);
        textureView.setOnZoomViewListener(onZoomViewListener);
        textureView.setOnPtzControlTouchListener(ptzControlTouchListener);
        mediaSync.setOnMediaScaleChangedListener(scaleChangedListener);
        mediaSync.setResetListener(resetListener);
    }

    @Override
    protected void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        TGLog.d(TAG, "analogZoom newConfig.orientation "+newConfig.orientation);
        if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            RelativeLayout.LayoutParams params = new  RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.addRule(RelativeLayout.CENTER_IN_PARENT,RelativeLayout.TRUE);

            String uuid = (String)TGApplicationBase.getInstance().getGlobalObject(CUR_DEVICE_UUID);
            if (mDevice != null){
                uuid = mDevice.uuid;
            }
            if (StringUtils.isEmpty(uuid)){
                params.height = (int) getResources().getDimension(R.dimen.player_height);
            }else{
                int h = resolutionHelper.calHeight(mWidth);
                if (h == 0){
                    h = (int) getResources().getDimension(R.dimen.player_height);
                }
                params.height = h;
            }
            textureView.setLayoutParams(params);
            if (isForeSightEnable){
                foreSightView.setVisibility(VISIBLE);
            }
        }else {
            RelativeLayout.LayoutParams params = new  RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            params.addRule(RelativeLayout.CENTER_IN_PARENT,RelativeLayout.TRUE);
            textureView.setLayoutParams(params);
            foreSightView.setVisibility(GONE);
        }
    }
}
